#include "crack.h"
#include "DES.h"

/* Checks if a candidate key is correct for a given left-right pair */
int check_key(uchar* Li, uchar* Ri, uchar* Kj, uchar* Rj) {
  /* Create a temp buffer to store output of feistel cipher */
  uchar f_out[4];

  /* Perform feistel cipher on Ri & candidate key */
  feistel(Ri, Kj, f_out);

  /* Compare if f(Ri,Kj) ^ Li == Rj */
  int k;
  for(k=0; k<4; k++) {
    if((f_out[k] ^ Li[k]) != Rj[k])
    return 0;
  }

  /* If all were equal it means that candidate key was correct */
  return 1;
}

/* Performs the Feistel Cipher */
void feistel(uchar* Ri, uchar* Kj, uchar* f_out) {

  /* Perform 32-bit to 48-bit expansion */
  uchar e_out[6];
  Permute(e_out, Ri, DataExpansion, 6);

  /* XOR with key */
  uchar s_in[6];
  int i;
  for(i=0; i<6; i++) {
    s_in[i] = e_out[i] ^ Kj[i];
  }

  /* Perform S-box operations */
  uchar s_out[4];
  sbox(s_out, s_in);
  /* Perform P-box permutation */
  Permute(f_out, s_out, PBox, 4);  

}
